import { Statistic, Row, Col, Popover, Modal, Image } from 'antd';
import AuthModal, { AuthResult } from '@/pages/pc/components/AuthModal';
import { history, Link, useHistory, useModel, useLocation } from 'umi';
import styles from './index.less';
import classNames from 'classnames';
import { useEffect, useState } from 'react';
import Reward from '@/pages/pc/components/Reward';
import { useLoginStatus } from '@/hooks/login';
import { allGet } from '@/services/pc';
import VideoPlayerModal from '../VideoPlayer';
import Image2 from '@/pages/pc/components/Image';
import moment from 'moment';
import { formatDateBeForeZeroPoint, isYsClass } from '@/utils';
import { CLASS_TYPE_MAP } from '@/common/const';
import WorkTable from '@/pages/pc/lecturer/upload-courses/components/table';
import MaterialModal from '@/pages/pc/components/MaterialModal';
import PackageC from '@/pages/pc/components/Package';
import { WECHAT_NUMBER } from '@/common/const';
import Countdown from 'react-countdown';

const useQuery = () => {
  const { search } = useLocation();
  return new URLSearchParams(search);
};
// 套餐搭配
const Package = (props) => {
  const query = useQuery();
  const mentor = query.get('mentor') || '';
  const [data] = useState(props.data);
  if (!data) return null;
  const newData =
    data?.map((item) => ({
      ...item,
      mentor: mentor,
      courses: Object.values(item.courses) || [],
    })) || [];

  return (
    <section className={styles.package}>
      <div className={styles.title}>
        <i className={styles.icon} />
        <div className={styles.text}>一步到位 · 超值组合</div>
        <div className={styles.subtext}>One Step to the Point · Value Combination</div>
      </div>
      <div className={styles.body}>
        <PackageC data={newData} itemKey="sid" />
      </div>
    </section>
  );
};

const Wxshare = (props) => {
  const { userInfo } = useModel('user');
  let url = `${location.origin}/center/courses/detail/${props.classId}`;
  if (userInfo.uid) {
    url = `${url}?shareuid=${userInfo.uid}`;
  }
  console.log(url);
  const img = `https://www.cgjoy.com/app.php?mod=train&do=qrcode&version=pc1.0&url=${encodeURIComponent(
    url,
  )}`;
  return (
    <div className={styles.wxsharemain}>
      <img loading="lazy" src={img} width="134" height="134" alt="" />
      <div className={styles.title}>
        <img loading="lazy" src={require('./images/icon-wx.png')} alt="" width="19" />
        微信扫码分享
      </div>
    </div>
  );
};

const More = (props) => {
  const { userInfo } = useModel('user');
  const handleEdit = () => {
    history.push(`/center/upload-courses?classid=${props.classId}`);
  };
  return (
    <div className={styles.moremain}>
      <a className={styles.item} href="/contract" target="_blank">
        预览合同
      </a>
      {userInfo.isadmin == 1 && (
        <div className={styles.item} onClick={handleEdit}>
          编辑课程
        </div>
      )}
    </div>
  );
};

interface CourseProps {
  data: any;
  /**
   * 1 秒杀
   * 2 预售
   * 3 正常
   */
  type: 1 | 2 | 3;
  /**
   * 1 学员
   * 2 讲师
   * 3 学员学习中心
   */
  role: 1 | 2 | 3;
  onBuy?: () => void;
  onLike?: () => void;
  hasRewrad?: boolean;
  classId?: any;
  className?: string;
  query?: any;
  onClick?: () => void;
  needClient?: boolean;
  clientOk?: boolean;

  /**
   * 赠品数量是否是实时库存
   */
  zpnumRealTime?: boolean;

  // 是否显示审核状态
  showApplyStatus?: boolean;

  isPreview?: boolean;
}
const MyCountdown = ({ onFinish, value }) => {
  const renderer = (obj) => {
    console.log(obj);
    const { days, hours, minutes, seconds } = obj.formatted;
    return (
      <div className={styles.myCountdownValue}>
        <span className={styles.myCountdownValuetitle}>距结束</span>
        {obj.days ? (
          <>
            <span className={styles.item}>{days}</span>
            <span className={styles.maohao}>天</span>
          </>
        ) : null}
        <span className={styles.item}>{hours}</span>
        <span className={styles.maohao}>:</span>
        <span className={styles.item}>{minutes}</span>
        <span className={styles.maohao}>:</span>
        <span className={styles.item}>{seconds}</span>
      </div>
    );
  };
  return <Countdown date={value} renderer={renderer} onComplete={onFinish} />;
};

const Course: React.FC<CourseProps> = ({
  className,
  type: propsType,
  onBuy,
  onLike,
  role = 1,
  hasRewrad = true,
  children,
  classId = 0,
  query,
  needClient = false,
  clientOk = false,
  zpnumRealTime = false,
  data = {},
  onClick,
  showApplyStatus,
  isPreview,
}) => {
  const { userInfo } = useModel('user');
  const [type, setType] = useState(propsType);
  // const deadline = Date.now() + 1000 * 60 * 60 * 24 + 1000 * 30;
  const history = useHistory();
  const [dataSource, setDataSource] = useState<any[]>([]);
  const [workTableVisible, setWorkTableVisible] = useState<boolean>(false);
  const [workTableLoading, setWorkTableLoading] = useState<boolean>(true);
  const handleCountdownFinish = () => {
    setType(3);
  };
  const [materialModalShow, setMaterialModalShow] = useState(false);
  useEffect(() => {
    // const deadline = data?.secskills?.secskilldead ? data?.secskills?.secskilldead * 1000 : 0;
    // if (propsType === 1 && deadline && Date.now() >= deadline) {
    //   setType(3);
    // }
    // 如果是秒杀类型， data?.secskill不存在或者data?.secskill?.stop == 1 就是秒杀没了，要变成正常课程类型3
    if (propsType === 1 && (!data?.secskill || data?.secskill?.stop == 1)) {
      setType(3);
    }
  }, []);
  const renderPrice = () => {
    const deadline = data?.secskills?.secskilldead ? data?.secskills?.secskilldead * 1000 : 0;
    if (type === 1) {
      return (
        <div className={styles.newmsWrapper}>
          <div className={styles.title}>
            秒杀！秒杀！限时抢购中{' '}
            {deadline > 0 && <MyCountdown value={deadline} onFinish={handleCountdownFinish} />}
          </div>
          <div className={styles.innerWrapper}>
            <div className={styles.msj}>秒杀价：¥{data?.secskills?.secskillprice}</div>
            <div className={styles.yj}>原价：¥{data?.price}</div>
          </div>
        </div>
        // <div className={styles.newms}>
        //   <div className={styles.title}>全网低价</div>
        //   <div className={styles.row}>
        //     <div className={styles.price}>
        //       <div className={styles.text}>秒杀价</div>¥
        //       <div className={styles.num}>{data?.secskills?.secskillprice}</div>
        //     </div>
        //   </div>
        // </div>
      );
    }
    if (type === 2) {
      return (
        <div className={styles.newysWrapper}>
          <div className={styles.title}>
            课程预售、限时低价
            <img src={require('./images/icon-stime.png')} alt="限制时间" width={99} />
          </div>
          <div className={styles.innerWrapper}>
            <div className={styles.ysj}>预售价：¥{data?.bookprice}</div>
            <div className={styles.yj}>原价：¥{data?.price}</div>
          </div>
        </div>
      );
    }

    return (
      <div className={classNames(styles.priceWrapper, styles[`priceWrapper-${type}`])}>
        <div className={styles.price}>¥{!needClient ? data.topay : clientOk ? data.topay : ''}</div>
        {data.topay !== data.price && (
          <div className={styles.oldprice}>
            原价：¥{!needClient ? data.price : clientOk ? data.price : ''}
          </div>
        )}
      </div>
    );
  };
  const renderBottomPrice = () => {
    if (type === 1) {
      return (
        <div className={styles.ms}>
          <div className={styles.title}>全网低价</div>
          <div className={styles.row}>
            <div className={styles.price}>
              <div className={styles.text}>秒杀价</div>¥
              <div className={styles.num}>{data?.secskills?.secskillprice}</div>
            </div>
          </div>
        </div>
      );
    }
    if (type === 2) {
      return (
        <div className={styles.ys}>
          <div className={styles.row}>
            <div className={styles.price}>
              <div className={styles.text}>预售价</div>¥
              <div className={styles.num}>{data?.bookprice}</div>
            </div>
          </div>
        </div>
      );
    }
    return null;
  };

  const renderRightPrice = () => {
    if (role === 3) return null;
    if (type === 1) {
      const deadline = data?.secskills?.secskilldead ? data?.secskills?.secskilldead * 1000 : 0;
      return (
        <div className={styles.momeyWrapper}>
          <div className={styles.preferentialPrice}>
            秒杀价<span className={styles.unit}>¥</span>
            <span className={styles.text}>{data?.secskills?.secskillprice}</span>
            {deadline > 0 && <MyCountdown value={deadline} onFinish={handleCountdownFinish} />}
            {/* <div className={styles.xl}>
            限量：27
          </div> */}
          </div>
        </div>
      );
    }
    if (type === 2) {
      return (
        <div className={classNames(styles.momeyWrapper, styles.ys)}>
          <div className={styles.preferentialPrice}>
            预售价 <span className={styles.unit}>¥</span>
            <span className={styles.text}>{data?.bookprice}</span>
          </div>
        </div>
      );
    }
    if (type === 3) {
      return (
        <div className={classNames(styles.momeyWrapper, styles.pt)}>
          <div className={styles.preferentialPrice}>
            售价 <span className={styles.unit}>¥</span>
            <span className={styles.text}>
              {!needClient ? data.price : clientOk ? data.price : ''}
            </span>
          </div>
        </div>
      );
    }
    return null;
  };

  // 点击购买
  const handleBuyClick = async () => {
    onBuy?.();
  };

  // 学员作业
  const handleGoWork = async () => {
    window.open(
      `/center/detail/works/1?classid=${classId}&classname=${encodeURIComponent(
        data.name,
      )}&order=bid`,
    );
  };

  // 点击喜欢
  const handleLikeClick = async () => {
    await allGet({ params: { mod: 'course', do: 'learn', classid: classId, version: 'pc1.0' } });
    onLike?.();
  };

  // 编辑课程
  const handleEditClass = async () => {
    // window.open(`/center/upload-courses?classid=${classId}`);
    history.push(`/center/upload-courses?classid=${classId}`);
  };
  // 添加课时
  const handleAddClass = async () => {
    window.open(`/center/upload-courses?classid=${classId}&tabindex=1`);
  };

  // 布置作业
  const handleAddWorks = async () => {
    console.log(classId);
    await getDetails();
    setWorkTableVisible(true);
  };
  // 获取详情
  const getDetails = async () => {
    setWorkTableLoading(true);
    const response = await allGet({
      params: { mod: 'course', do: 'post', version: 'pc1.0', classid: classId /* classid */ },
    });
    if (response.success) {
      const { chapters = [] } = response.data;
      // console.log(2222, allCl);
      let chapters_1: any[] = [];
      let othersLessons_1: any[] = [];
      chapters.forEach((item, index) => {
        if (Number(item.cid) === 0) {
          othersLessons_1 = (item.children ?? []).map((it, i, arr) => {
            if (i > 0) {
              it.beforeIndex = arr[i - 1].displayorder;
            }
            if (i < arr.length - 1) {
              it.afterIndex = arr[i + 1].displayorder;
            }
            return it;
          });
        } else {
          chapters_1.push({
            ...item,
            children: (item.children ?? []).map((it, i, arr) => {
              if (i > 0) {
                it.beforeIndex = arr[i - 1].displayorder;
              } else if (i < arr.length - 1) {
                it.afterIndex = arr[i + 1].displayorder;
              }
              return it;
            }),
          });
        }
      });
      setDataSource([...chapters_1, ...othersLessons_1]);
      setWorkTableLoading(false);
    }
  };

  // 关闭作业弹窗
  const onCloseWorkTable = () => {
    setWorkTableVisible(false);
    setDataSource([]);
  };
  const hasFreeClass = (chapters = []) => {
    let childrenArr = [];
    chapters.forEach((item: any) => {
      childrenArr = [...childrenArr, ...(item.children || [])];
    });
    const lid = childrenArr.find((item) => item.type === '-1')?.lid;

    return lid;
  };
  const handleDownload = () => {
    setMaterialModalShow(true);
  };

  const handleLearn = () => {
    // 免认证免签
    if (data.nocontract == 1) {
      return window.open(`/center/video/player/${data.classid}`);
    }
    if (userInfo.verify !== 1) {
      AuthModal.show({
        onSuccess: async (values, type) => {
          window.location.reload();
        },
      });
      return;
    }
    if (data.contract != 1) {
      return AuthResult.show({
        buttonText: '签署合同',
        title: '请先签署合同',
        onClick: () => {
          window.location.href = '/learning?index=3';
        },
      });
    }

    window.open(`/center/video/player/${data.classid}`);
  };

  const handleGoRoom = () => {
    window.open(data.showroom);
  };

  const renderNewButtons = () => {
    const hasKc = data?.secskill?.stop != 1;
    const haswork = Number(data?.worknum) > 0;
    const hasPayed = data.payed == true;
    if (!clientOk) {
      return null;
    }
    return (
      <div className={styles.newButtons}>
        {hasPayed ? (
          <div className={classNames(styles.newButton, styles.xuexi)} onClick={handleLearn}>
            开始学习
          </div>
        ) : hasKc ? (
          <div className={classNames(styles.newButton, styles.buy)} onClick={handleBuyClick}>
            立即购买
          </div>
        ) : (
          <div
            className={classNames(styles.newButton, styles.buy, styles.disabled)}
            onClick={handleBuyClick}
          >
            库存不足
          </div>
        )}
        {data.showroom && (
          <div className={classNames(styles.newButton, styles.jiaoshi)} onClick={handleGoRoom}>
            进入教室
          </div>
        )}
        {haswork && (
          <div className={classNames(styles.newButton, styles.work)} onClick={handleGoWork}>
            学员作业
          </div>
        )}
      </div>
    );
  };

  const isLogin = useLoginStatus();

  const handleShowVideo = (e) => {
    e.stopPropagation();
    VideoPlayerModal.showList({
      data: [{ url: data.video }],
    });
  };
  const renderYh = () => {
    if (type === 1) return null;
    const arr: any[] = [];
    const { coupons, students } = data;
    if (coupons?.commoncouponamount && coupons?.commoncoupondead) {
      const commoncoupondead = formatDateBeForeZeroPoint(coupons?.commoncoupondead * 1000);
      if (moment().isBefore(moment(commoncoupondead))) {
        arr.push(
          <div className={styles.item} key="commoncouponamount">
            通用券{coupons.commoncouponamount}元
          </div>,
        );
      }
    }
    if (students?.studentreduce && students?.studentdead && userInfo.isstudent) {
      const studentdead = formatDateBeForeZeroPoint(students?.studentdead * 1000);
      if (moment().isBefore(moment(studentdead))) {
        arr.push(
          <div className={styles.item} key="sharecouponamount2">
            老学员优惠{students.studentreduce}元
          </div>,
        );
      }
    }
    if (coupons?.sharecouponamount && coupons?.sharecoupondead) {
      const sharecoupondead = formatDateBeForeZeroPoint(coupons?.sharecoupondead * 1000);
      if (moment().isBefore(moment(sharecoupondead))) {
        arr.push(
          <div className={styles.item} key="sharecouponamount1">
            分享得优惠券{coupons.sharecouponamount}元
          </div>,
        );
      }
    }

    return arr.length > 0 ? <div className={styles.newYhWrapper}>{arr}</div> : null;
  };
  const renderZp = (hasRow = false) => {
    const rewards = data.rewards;
    if (rewards?.type === 'gift' && Array.isArray(rewards?.gifts) && rewards?.gifts?.length > 0) {
      const gifts = rewards?.gifts || [];
      if (zpnumRealTime && gifts.every((item) => item.limit - data.givegifted <= 0)) {
        return null;
      }
      return (
        <div className={styles.zp}>
          <div className={styles.text}>
            <i className={styles.icon} />
            赠品：
          </div>
          {gifts.map((item) => {
            const num = zpnumRealTime ? item.limit - data.givegifted : item.limit;
            return (
              <div className={styles.item} key={item.aid}>
                <Image2
                  src={item.pic}
                  width="26"
                  height="26"
                  text={
                    <div>
                      <div>购买后联系客服，截图购买订单</div>
                      <div>告知想要的赠品和收货地址</div>
                    </div>
                  }
                  className={styles.img}
                />
                {item.limit && `x${num}`}
              </div>
            );
          })}
        </div>
      );
    }
    if (rewards?.type === 'credit') {
      if (zpnumRealTime && rewards?.limit - data.givegifted <= 0) {
        return null;
      }
      const num = zpnumRealTime ? rewards?.limit - data.givegifted : rewards?.limit;
      return (
        <div className={styles.zp}>
          <div className={styles.text} style={hasRow ? { marginLeft: 0 } : {}}>
            赠品：
          </div>
          <div className={styles.item}>
            <Image
              src={require('./images/iocn-cg-quan.png')}
              alt=""
              className={styles.imgcg}
              rootClassName={styles.previewImg}
            />
            <span className={styles.cg}> {rewards?.amount}CG券</span>x{num}
          </div>
        </div>
      );
    }
    return null;
  };

  const handleClickTitle = () => {
    onClick?.();
  };
  const handleClickPic = () => {
    onClick?.();
  };
  const services = data?.services?.split(',').filter((item) => item) || [];
  return (
    <div
      className={classNames(
        'cgjoy--course-detail',
        styles.container,
        styles[`course${role}`],
        className,
      )}
    >
      {/* "-2"=>已关闭
        "-1"=>审核中
        "0"=>审核通过
        "1"=>正在开课
        "2"=>已结课
        "3"=>停止出售 */}
      <Modal
        wrapClassName="c-lecturer-chapter-modal-wrap-container"
        visible={workTableVisible}
        footer={false}
        onCancel={onCloseWorkTable}
        destroyOnClose
        width={800}
        maskClosable={false}
      >
        <WorkTable
          key={classId}
          isModal
          loading={workTableLoading}
          classid={classId}
          reload={getDetails}
          dataSource={dataSource}
        />
      </Modal>
      <div className={classNames('cgjoy--course-main', styles.detail)}>
        {userInfo.isadmin == 1 ? (
          <div className={styles.qishu}>{data.qi}</div>
        ) : (
          <div className={styles.qishue} />
        )}
        <div
          className={classNames(styles['course-title'], 'course-detail-title')}
          onClick={handleClickTitle}
        >
          {data.name}
        </div>
        <div className={styles['course-info']}>
          <i className={styles['course-info-leftbg']} />
          <div className={styles.soft}>
            课程用到的软件：{Array.isArray(data.softids) ? data.softids.join('、') : '-'}
          </div>
          <Link
            to={`/teachers/detail/${data.uid}`}
            className={classNames(styles.teacher, 'cgjoy--course-detail-teacher')}
          >
            <i className={styles.avatar} style={{ backgroundImage: `url(${data.avatar})` }} />
            <div className={styles.text}>{data.username} 老师</div>
          </Link>
        </div>
        {renderPrice()}
        <div className={styles.newButtonsWapper}>
          {renderNewButtons()}
          {data.payed && data.invitebuys?.cashbacks > 0 ? (
            <Reward
              data={data.invitebuys}
              classDetail={data}
              className={classNames(styles.reward, 'course-detail-reward')}
            />
          ) : null}
        </div>

        <div className={styles.someWrapper}>
          <div className={styles.itemWrapper}>
            <div className={styles.item}>
              <i className={classNames(styles.icon, styles.iconxue)} />
              {data.viewnum}人想学
            </div>

            {userInfo.isadmin == 1 && (
              <>
                <div className={styles.item}>
                  <i className={classNames(styles.icon, styles.iconbaoming)} />
                  报名 {data.enrollnum || 0}
                </div>
                <div className={styles.item}>
                  <i className={classNames(styles.icon, styles.iconyishou)} />
                  已售 {data.studentnums || 0}
                </div>
                <div className={styles.item}>
                  <i className={classNames(styles.icon, styles.iconshijian)} />
                  {data.dateline}
                </div>
              </>
            )}
          </div>
          {renderZp()}
        </div>
        {renderYh()}

        {!isPreview && <Package data={data?.salesmix} />}
        {services.length > 0 && (
          <div className={styles.serverWrapper}>
            {services.map((item) => (
              <div className={styles.item} key={item}>
                <i className={styles.icon} />
                {item}
              </div>
            ))}
          </div>
        )}
      </div>
      {children}
      {materialModalShow && (
        <MaterialModal attachs={data?.attachs} onClose={() => setMaterialModalShow(false)} />
      )}
    </div>
  );
};
export default Course;
